package com.xjscrm.console.chat.core.impl.conversation;

import com.xjscrm.console.chat.core.ChatBaseMsgHandler;
import com.xjscrm.console.chat.enums.ChatMsgType;
import com.xjscrm.console.chat.frame.recv.RConversationExpireMsg;
import com.xjscrm.console.chat.frame.send.SResultMsg;
import com.xjscrm.console.entity.ChatTalkSession;
import com.xjscrm.console.service.customer.chat.ChatDispatchSettingsService;
import com.xjscrm.console.service.customer.chat.ChatTalkSessionService;
import com.xjscrm.console.service.customer.chat.ChatTalkSessionStaffRelService;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @author mingyang.chen create in 2024/3/17 09:42
 */
@Component
@Slf4j
public class ChatConversationExpireMsgHandler extends ChatBaseMsgHandler<RConversationExpireMsg> {

    @Autowired
    private ChatTalkSessionService chatTalkSessionService;

    @Autowired
    private ChatTalkSessionStaffRelService chatTalkSessionStaffRelService;

    @Autowired
    private ChatDispatchSettingsService chatDispatchSettingsService;

    @Override
    public Class<RConversationExpireMsg> msgClass() {
        return RConversationExpireMsg.class;
    }

    @Override
    public boolean checkMsg(RConversationExpireMsg baseMsg) {
        return super.checkMsg(baseMsg) || !ObjectUtils.isNotEmpty(baseMsg.getTalkSessionId());
    }

    @Override
    public SResultMsg doHandle(RConversationExpireMsg content, ChannelHandlerContext ctx) {
        Long merId = content.getMerId();
        Long talkSessionId = content.getTalkSessionId();
        Long staffId = content.getStaffId();

        ChatTalkSession talkSession = chatTalkSessionService.getById(merId, talkSessionId);
        if (Objects.isNull(talkSession)) {
            return SResultMsg.fail(content, "会话标记过期失败: 会话不存在");
        }
        chatTalkSessionStaffRelService.markSessionRelExpire(content.getMerId(), staffId, talkSession.getDeviceUniqueId(), talkSession.getId());
        //
        chatTalkSessionService.delChatRecvDelayTask(merId, staffId, talkSession);
        chatTalkSessionService.delChatSendDelayTask(merId, staffId, talkSession);
        //
        return SResultMsg.success(content, "success");
    }

    @Override
    public ChatMsgType msgType() {
        return ChatMsgType.r_conversation_expire;
    }
}
